package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.codec.Base64;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ims.v20201229.ImsClient;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationRequest;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationResponse;
import com.tencentcloudapi.tms.v20201229.TmsClient;
import com.tencentcloudapi.tms.v20201229.models.TextModerationRequest;
import com.tencentcloudapi.tms.v20201229.models.TextModerationResponse;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Autowired
    private VodUploadClient vodUploadClient;

    /**
     * 上传音视频文件到腾讯云点播平台
     *
     * @param file
     * @return {mediaFileId:文件唯一标识,mediaUrl:文件播放地址}
     */
    @Override
    public Map<String, String> uploadTrack(MultipartFile file) {
        try {
            //1.将用户文件存到本地服务器
            String uploadTempPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);

            //2.构建上传请求对象VodUploadRequest
            VodUploadRequest request = new VodUploadRequest();
            request.setMediaFilePath(uploadTempPath);

            //3.调用上传方法将音视频文件上传到点播平台
            VodUploadResponse uploadResponse = vodUploadClient.upload(vodConstantProperties.getRegion(), request);

            //4.解析上传结果，获取音视频mediaFileId和mediaUrl
            if (uploadResponse != null) {
                String fileId = uploadResponse.getFileId();
                String mediaUrl = uploadResponse.getMediaUrl();
                Map<String, String> map = new HashMap<>();
                map.put("mediaFileId", fileId);
                map.put("mediaUrl", mediaUrl);

                return map;

            }

            return null;
        } catch (Exception e) {
            log.error("文件上传点播平台失败,{}", e);
            throw new GuiguException(500, "文件上传点播平台失败");
        }
    }

    /**
     * 调用腾讯点播平台-获取音频文件时长、大小、类型
     *
     * @param mediaFiledId
     * @return
     */
    @Override
    public TrackMediaInfoVo getMediaInfo(String mediaFiledId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
            String[] fileIds1 = {mediaFiledId};
            req.setFileIds(fileIds1);

            //4.调用接口，返回的resp是一个DescribeMediaInfosResponse的实例，与请求对象对应
            DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
            //5.解析响应对象：
            if (resp != null) {
                MediaInfo mediaInfo = resp.getMediaInfoSet()[0];
                //5.1基本信息：包括媒体名称、分类、播放地址、封面图片等。
                MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                String type = basicInfo.getType();

                //5.2元信息：包括大小、时长、视频流信息、音频流信息等。
                MediaMetaData metaData = mediaInfo.getMetaData();
                Float duration = metaData.getDuration();
                Long size = metaData.getSize();

                //5.3 封装TrackMediaInfoVo
                TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();
                trackMediaInfoVo.setDuration(duration);
                trackMediaInfoVo.setSize(size);
                trackMediaInfoVo.setType(type);

                return trackMediaInfoVo;

            }

        } catch (Exception e) {
            log.error("获取腾讯点播平台获取音频详情异常:{}", e);
            throw new RuntimeException(e);
        }

        return null;
    }

    /**
     * 发起音视频文件的审核任务
     *
     * @param mediaFileId
     * @return 发起审核任务的id
     */
    @Override
    public String startAuditReviewTask(String mediaFileId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            ReviewAudioVideoRequest req = new ReviewAudioVideoRequest();
            req.setFileId(mediaFileId);

            //4.返回的resp是一个ReviewAudioVideoResponse的实例，与请求对象对应
            ReviewAudioVideoResponse resp = client.ReviewAudioVideo(req);

            //5.解析结果
            if (resp != null) {
                String taskId = resp.getTaskId();
                return taskId;
            }

        } catch (Exception e) {
            log.error("发起音视频文件的审核任务异常:{}", e);
            throw new RuntimeException(e);
        }

        return null;
    }

    @Override
    public void deleteMedia(String mediaFileId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());

            //2.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());

            //3.实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);

            //4.返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            //执行删除
            DeleteMediaResponse resp = client.DeleteMedia(req);

        } catch (Exception e) {
            log.error("删除音视频文件异常:{}", e);
        }

    }

    /**
     * 根据审核任务id获取音视频文件的审核结果
     *
     * @param reviewTaskId
     * @return
     */
    @Override
    public String getReviewResult(String reviewTaskId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());

            //2.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());

            //3.实例化一个请求对象,每个接口都会对应一个request对象
            DescribeTaskDetailRequest req = new DescribeTaskDetailRequest();
            req.setTaskId(reviewTaskId);

            //4.返回的resp是一个DescribeTaskDetailResponse的实例，与请求对象对应
            DescribeTaskDetailResponse resp = client.DescribeTaskDetail(req);
            if (resp != null) {
                //4.1 判断任务类型是否为音视频审核任务
                String taskType = resp.getTaskType();
                if ("ReviewAudioVideo".equals(taskType)) {

                    //4.2 获取审核任务状态
                    ReviewAudioVideoTask reviewAudioVideoTask = resp.getReviewAudioVideoTask();
                    if ("FINISH".equals(reviewAudioVideoTask.getStatus())) {

                        //4.3 获取音视频审核任务的输出结果，从结果中获取建议
                        String suggestion = reviewAudioVideoTask.getOutput().getSuggestion();
                        //统一都转换成小写字母，方便后续业务处理
                        return suggestion.toLowerCase();
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取审核结果失败:{}", e);
        }
        return null;
    }

    /**
     * 对文本内容进行审核
     *
     * @param content 注意：该字段表示待检测对象的文本内容，
     *                文本需要按utf-8格式编码，长度不能超过10000个字符（按unicode编码计算），
     *                并进行 Base64加密
     * @return
     */
    @Override
    public String scanContent(String content) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());

            //2.实例化要请求产品的client对象,clientProfile是可选的
            TmsClient client = new TmsClient(cred, vodConstantProperties.getRegion());

            //3.实例化一个请求对象,每个接口都会对应一个request对象
            TextModerationRequest req = new TextModerationRequest();
            req.setContent(Base64.encode(content.getBytes()));

            //4.返回的resp是一个TextModerationResponse的实例，与请求对象对应
            TextModerationResponse resp = client.TextModeration(req);

            //5.解析审核结果
            if (resp != null) {
                String suggestion = resp.getSuggestion();
                return suggestion.toLowerCase();
            }

        } catch (Exception e) {
            log.error("[专辑服务]文本审核异常:{}", e);
            throw new RuntimeException(e);
        }

        return null;
    }

    /**
     * 图片审核
     *
     * @param file 图片文件
     * @return
     */
    @Override
    public String scanImage(MultipartFile file) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());

            //2.实例化要请求产品的client对象,clientProfile是可选的
            ImsClient client = new ImsClient(cred, vodConstantProperties.getRegion());

            //3.实例化一个请求对象,每个接口都会对应一个request对象
            ImageModerationRequest req = new ImageModerationRequest();
            req.setFileContent(Base64.encode(file.getInputStream()));

            //4.发送图片请求，返回的resp是一个ImageModerationResponse的实例，与请求对象对应
            ImageModerationResponse resp = client.ImageModeration(req);

            //5.解析对象
            if (resp != null) {
                String suggestion = resp.getSuggestion();
                return suggestion.toLowerCase();
            }

        } catch (Exception e) {
            log.error("[专辑服务]图片审核异常:{}", e);
            throw new RuntimeException(e);
        }
        return null;

    }

}
